package com.warehouse.util;

import com.alibaba.fastjson.JSON;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class GetQRCode {

    private static void getURCodePicyure(String c ,String path){
        int width = 200; //定义图片宽度
        int height = 200; // 定义图片高度
        String type = "png"; //定义图片格式
        String content = c; //图片扫描二维码的内容

        //使用HahsMap进行二维码的配置
        HashMap hashMap = new HashMap();
        //定义字符集设计为utf-8
        hashMap.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        // 设计容错等级
        hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置边距
        hashMap.put(EncodeHintType.MARGIN,1);

        try {
            //生成二维码对象，传递各种属性
            BitMatrix bitMatrix = new MultiFormatWriter()
                    .encode(content, BarcodeFormat.QR_CODE, width, height, hashMap);
            // 定义路径
            Path file = new File(path).toPath();
            try {
                MatrixToImageWriter.writeToPath(bitMatrix,type,file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }



    /**
     * 生成二维码
     * @param url 后台url
     * @param map 二维码内容
     * */
    public static String getCode( Map<String, Object> map) throws IOException {
        String string = UUID.randomUUID().toString();
        String c = JSON.toJSONString(map);
        getURCodePicyure(c,"src/main/resources/static/images/"+string+".png");
        return "images/"+string+".png";
    }

    public static void main(String[] args) {
        getURCodePicyure("123456","src/main/resources/static/images/"+"string"+".png");
    }
}
